<template>
  <div class="budgets-container">
    <div class="add-budget">
      <h2>添加预算</h2>
      <form @submit.prevent="addBudget">
        <label>
          金额:
          <input type="number" v-model="newBudget.amount">
        </label>
        <label>
          开始日期:
          <input type="date" v-model="newBudget.start_date">
        </label>
        <label>
          结束日期:
          <input type="date" v-model="newBudget.end_date">
        </label>
        <label>
          类别:
          <input type="text" v-model="newBudget.category">
        </label>
        <label>
          描述:
          <input type="text" v-model="newBudget.description">
        </label>
        <button type="submit">添加</button>
      </form>
    </div>

    <h2>预算列表</h2>
    <div v-if="loading" class="loading-message">加载中...</div>
    <div v-else-if="error" class="error-message">{{ error }}</div>
    <ul v-else>
      <li v-for="budget in sortedBudgets" :key="budget.budget_id">
        <div>金额: {{ formatAmount(budget.amount) }}</div>
        <div>开始日期: {{ formatDate(budget.start_date) }}</div>
        <div>结束日期: {{ formatDate(budget.end_date) }}</div>
        <div>类别: {{ budget.category }}</div>
        <div>描述: {{ budget.description }}</div>
        <button @click="deleteBudget(budget.budget_id)">删除</button>
        <button @click="editBudgetModal(budget)">编辑</button>
      </li>
    </ul>

    <!-- 编辑预算的模态框 -->
    <div v-if="editModalVisible" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeEditModal">&times;</span>
        <h2>编辑预算</h2>
        <form @submit.prevent="updateBudget">
          <label>
            金额:
            <input type="number" v-model="editedBudget.amount">
          </label>
          <label>
            开始日期:
            <input type="date" v-model="editedBudget.start_date">
          </label>
          <label>
            结束日期:
            <input type="date" v-model="editedBudget.end_date">
          </label>
          <label>
            类别:
            <input type="text" v-model="editedBudget.category">
          </label>
          <label>
            描述:
            <input type="text" v-model="editedBudget.description">
          </label>
          <button type="submit">保存</button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.loadData()
    })
  },
  data () {
    return {
      budgets: [],
      loading: false,
      error: '',
      editModalVisible: false,
      editedBudget: {
        budget_id: null,
        amount: 0,
        start_date: '',
        end_date: '',
        category: '',
        description: ''
      },
      newBudget: {
        amount: 0,
        start_date: '',
        end_date: '',
        category: '',
        description: ''
      }
    }
  },
  methods: {
    async loadData () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      this.loading = true
      try {
        const response = await axios.get('/budgets', config)
        this.budgets = response.data
        this.loading = false
      } catch (error) {
        this.handleError(error)
      }
    },
    handleError (error) {
      this.error =
        error.response && error.response.data.message
          ? error.response.data.message
          : '网络错误，请检查您的网络连接'
      this.loading = false
      console.error('获取预算失败:', error.response ? error.response.data.message : error.message)
    },
    formatAmount (amount) {
      return `￥${amount.toFixed(2)}`
    },
    formatDate (date) {
      if (typeof date === 'string') {
        date = new Date(date)
      }
      if (!date || !(date instanceof Date) || isNaN(date.getTime())) {
        console.error('Invalid date object:', date)
        return ''
      }
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`
    },
    async addBudget () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      this.loading = true
      try {
        const response = await axios.post('/budgets', this.newBudget, config)
        this.budgets.push(response.data)
        this.newBudget = {
          amount: 0,
          start_date: '',
          end_date: '',
          category: '',
          description: ''
        }
        this.loading = false
      } catch (error) {
        this.handleError(error)
      }
    },
    deleteBudget (budgetId) {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      this.loading = true
      axios
        .delete(`/budgets/${budgetId}`, config)
        .then(() => {
          this.budgets = this.budgets.filter((budget) => budget.budget_id !== budgetId)
          this.loading = false
        })
        .catch((error) => {
          this.handleError(error)
        })
    },
    editBudgetModal (budget) {
      this.editedBudget = { ...budget }
      this.editModalVisible = true
    },
    closeEditModal () {
      this.editModalVisible = false
    },
    async updateBudget () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      this.loading = true
      try {
        await axios.put(`/budgets/${this.editedBudget.budget_id}`, this.editedBudget, config)
        this.closeEditModal()
        await this.loadData()
      } catch (error) {
        this.handleError(error)
      }
    }
  },
  computed: {
    sortedBudgets () {
      return this.budgets
    }
  }
}
</script>

<style scoped>
.budgets-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

li div {
  margin-bottom: 5px;
}

button {
  margin-right: 5px;
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #f0f0f0;
}

.income {
  color: green;
}

.expense {
  color: red;
}

.loading-message,
.error-message {
  text-align: center;
  margin-top: 20px;
  font-style: italic;
  color: #555;
}

.add-budget {
  margin-bottom: 30px;
}

.add-budget form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.add-budget label {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-budget input,
.add-budget select {
  width: 60%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.add-budget button {
  align-self: center;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-budget button:hover {
  background-color: #66b1ff;
}

/* 编辑预算的模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  cursor: pointer;
}
</style>
